#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
闲云潭影日悠悠, 物换星移几度秋!
						--王勃
"""
from pyse import Pyse
from time import sleep

CSS_SUBMIT = "id=>J_SubmitQuick"
# CSS_USER_FORMAT = "css=>#J_QuickLogin > form > ul.ww-userlist > li:nth-child(%s) > label"
CSS_USER_FORMAT = "css=>#J_QuickLogin > form > ul.userlist > li:nth-child(%s) > label"

URL = "https://oauth.taobao.com/authorize?response_type=token&client_id=23398461&state=bkx&view=web"

def parseToken(url):
	"""

	从字符串中截取token
	"""
	if 'access_token=' in url:
		return url.split('access_token=')[1].split('&')[0]
	else:
		return None

def driverInit(loginUrl):
	"""

	打开浏览器
	"""
	driver = Pyse("ie")
	driver.open(loginUrl)
	print 'open'
	
	driver.element_wait("css", "#J_loginIframe", 5)
	
	url = driver.get_attribute("css=>#J_loginIframe", 'src')
	driver.open(url)

	driver.element_wait("css", "#J_QuickLogin", 5)

	return driver

def getToken(driver, n):
	"""

	获取Token
	"""
	driver.click( CSS_USER_FORMAT % n )
	driver.submit(CSS_SUBMIT)
	sleep(3)
	token = parseToken(driver.get_url())
	if not token:
		driver.F5()
		driver.click( CSS_USER_FORMAT % n )
		driver.submit(CSS_SUBMIT)
		sleep(3)
		token = parseToken(driver.get_url())
	return token

def getTokenFromAliUser(driver, aliUser):
	"""

	获取指定用户名的token
	"""
	n = 1
	token = None
	while True:
		try:
			userText = driver.get_text(CSS_USER_FORMAT % n)
			if userText == aliUser:
				token = getToken(driver, n)
				break
			n += 1
		except Exception as e:
			break
	return token

def getTokenFromAliUserList(driver, aliUserList):
	"""

	获取用户列表中的随机一个用户的token
	"""
	n = 1
	token = None
	userText = ''
	while True:
		try:
			userText = driver.get_text(CSS_USER_FORMAT % n)
		
			if userText in aliUserList:
				token = getToken(driver, n)
				break
	
			n += 1
		except Exception as e:
			break
	return userText, token

def userGetAlimamaSessionAccessToken(aliUser, loginUrl, tryTimes=1):
	"""

	获取指定用户名的token
	"""
	driver = driverInit(loginUrl)

	for i in range(tryTimes):
		token = getTokenFromAliUser(driver, aliUser)
		
		if not token: 
			driver.F5()
		else:
			break

	driver.close()
	return token

def postFuncTest(aliUser, token):
	print 'success'
	return True

def postToken(driver, aliUserList, postFunc):
	aliUser, token = getTokenFromAliUserList(driver, aliUserList)
	if token:
		if postFunc(aliUser, token):
			upStatus = '更新成功'
		else:
			upStatus = '更新失败: 原因是, 在提交服务器的时候'
		upText = '当前用户 (%s) Token更新状态: %s' % (aliUser.encode('utf-8'), upStatus)
		aliUserList.remove(aliUser)
		return True
	else:
		return False

def userListGetAlimamaSessionAccessToken(aliUserList, loginUrl, postFunc, tryTimes=1):
	"""

	获取用户列表中的随机一个用户的token, 前提是有登录旺旺
	"""
	while aliUserList and tryTimes > 0:
		driver = driverInit(loginUrl)
		if not postToken(driver, aliUserList, postFunc):
			refreshTime = 3
			while "css_style=oauth_login" in driver.get_url() and refreshTime > 1:
				refreshTime -= 1
				print 'refreshTime', refreshTime
				driver.F5()
				if postToken(driver, aliUserList, postFunc):
					break
		driver.close()
		tryTimes -= 1
		print 'tryTimes', tryTimes

	if aliUserList:
		aliUserListStr = ','.join([u.encode('utf-8') for u in aliUserList])
		print unicode('这些账号[%s]更新失败' % aliUserListStr, 'utf-8').encode('gbk')
	else:
		print unicode("所有账号更新成功", 'utf-8').encode('gbk')

def example():
	"""

	例子
	"""
	userList = [u'xmyanday', u'苦哈200']
	userListGetAlimamaSessionAccessToken(userList, URL, postFuncTest, 3)

if __name__ == '__main__':
	example()